using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using CMS.api.Entity;
using CMS.api.Model;
using CMS.api.Repository;
using CMS.api.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;

namespace CMS.api.Controllers
{

    [ApiController]
    [Route("[controller]")]
    public class IndexController : ControllerBase
    {
        /// <summary>
        /// 用户数据库增删改查的属性
        /// </summary>
        // 用户表
        private ICURDable<Users> _UsersRepository;
        // 文章表
        private ICURDable<Articles> _ArticlesRepository;
        // 文章分类表
        private ICURDable<Article_Category> _Article_CategoryRepository;
        // 文章评论表
        private ICURDable<Article_Comment> _Article_CommentRepository;
        // 文章内容表
        private ICURDable<Article_Content> _Article_ContentRepository;
        // 文章图片表
        private ICURDable<Article_Picture> _Article_PictureRepository;
        // 文章点赞表
        private ICURDable<Article_Like> _Article_LikeRepository;
        // 文章点反对表
        private ICURDable<Article_Low> _Article_LowRepository;
        // 文章浏览记录表
        private ICURDable<Article_View> _Article_ViewRepository;
        // 用于保存token的配置信息
        private TokenParameter _tokenParameter;
        // 用于读取配置文件的信息
        private readonly IConfiguration _configuration;

        public IndexController(
            IConfiguration configuration,
            ICURDable<Articles> ArticlesRepository,
            ICURDable<Article_Category> Article_CategoryRepository,
            ICURDable<Article_Comment> Article_CommentRepository,
            ICURDable<Article_Content> Article_ContentRepository,
            ICURDable<Article_Picture> Article_PictureRepository,
            ICURDable<Article_Like> Article_LikeRepository,
            ICURDable<Article_Low> Article_LowRepository,
            ICURDable<Article_View> Article_ViewRepository,
            ICURDable<Users> UsersRepository
        )
        {
            _ArticlesRepository = ArticlesRepository;
            _Article_CategoryRepository = Article_CategoryRepository;
            _Article_CommentRepository = Article_CommentRepository;
            _Article_ContentRepository = Article_ContentRepository;
            _Article_PictureRepository = Article_PictureRepository;
            _Article_LikeRepository = Article_LikeRepository;
            _Article_LowRepository = Article_LowRepository;
            _Article_ViewRepository = Article_ViewRepository;
            _UsersRepository = UsersRepository;

            _configuration = configuration;
            _tokenParameter =
                _configuration
                    .GetSection("TokenParameter")
                    .Get<TokenParameter>();
        }

        /// <summary>
        /// 根据评论Id删除评论
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("DeleteArticleById/{id}")]
        public dynamic DeleteArticleById(int id)
        {

            var comment = _Article_CommentRepository.Table.Where(x => x.Id == id).FirstOrDefault();
            comment.IsDeleted = true;

            var tmp = new
            {
                Code = 200,
                Data = comment,
                Msg = "删除评论成功"
            };

            return JsonHelper.Serialize(tmp);
        }



        /// <summary>
        /// 根据文章Id给文章发表评论
        /// </summary>
        /// <param name="aritcleComment">需要传入:UserId,ArticleId,ArticleCommentContent</param>
        /// <returns></returns>

        [HttpPost, Route("InsterComment/{id}")]
        public dynamic InsterArticleComment(int id, NewAritcleComment aritcleComment)
        {

            var userId = aritcleComment.UserId;
            var articleId = id;
            var articleCommentContent = aritcleComment.ArticleCommentContent;
            var token = aritcleComment.Token;

            if (token == null || string.IsNullOrEmpty(token))
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "请登录后再发表评论"
                };
                return JsonHelper.Serialize(tmp);
            }
            else if (string.IsNullOrEmpty(articleCommentContent))
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "请输入内容在发表评论"
                };
                return JsonHelper.Serialize(tmp);
            }
            else
            {
                var comment = new Article_Comment
                {
                    UserId = userId,
                    ArticleId = articleId,
                    ArticleCommentContent = articleCommentContent
                };
                _Article_CommentRepository.Inster(comment);


                var tmp = new
                {
                    Code = 200,
                    Data = comment,
                    Msg = "发表评论成功!"
                };
                return JsonHelper.Serialize(tmp);
            }


        }

        /// <summary>
        /// 根据文章Id查找当前文章的评论
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("ArticleComments/{id}")]
        public dynamic PostArticleCommentsByArticleId(int id)
        {
            // 查找当前文章的所有评论
            var articles = _Article_CommentRepository.Table.Where(x => x.ArticleId == id && x.IsDeleted == false).OrderByDescending(y => y.CreatedTime).ToList();

            // 根据查找得到评论中跟用户表进行连接查找出发出改条评论的是谁
            var articleComment = articles.Select(o =>
            {
                var u = _UsersRepository.Table.Where(x => x.Id == o.UserId).FirstOrDefault();
                return new
                {
                    commentId = o.Id,
                    userName = u.Username,
                    articleComment = o.ArticleCommentContent,
                    createTime = o.CreatedTime
                };
            });


            var tmp = new
            {
                Code = 200,
                Data = articleComment,
                Msg = "好像查到了哦"
            };

            return JsonHelper.Serialize(tmp);
        }

        /// <summary>
        /// 添加文章浏览记录
        /// </summary>
        /// <param name="view"></param>
        /// <returns></returns>
        [HttpPost, Route("InsterView/{id}")]
        public dynamic InsterArticleView(int id)
        {

            var userId = 1;
            var articleId = id;

            var v = new Article_View
            {
                UserId = userId,
                ArticleId = articleId,
                IsBrowse = true
            };
            _Article_ViewRepository.Inster(v);

            var tmp = new
            {
                Code = 200,
                Data = v,
                Msg = "浏览记录+1"
            };
            return JsonHelper.Serialize(tmp);

        }

        /// <summary>
        /// 文章点反对
        /// </summary>
        /// <param name="like">需要传入:UserId,ArticleId</param>
        /// <returns></returns>
        [HttpPost, Route("InsterLow")]
        public dynamic InsterArticleLow(NewLike_Low_View low)
        {
            // 查找当前用户是否给这个文章点过反对
            var isLow = _Article_LowRepository.Table.Where(x => x.UserId == low.UserId && x.ArticleId == low.ArticleId).FirstOrDefault();
            var token = low.Token;

            // 如果token不存在那么让他登录
            if (string.IsNullOrEmpty(token) || token == null)
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "您还未登录请登录"
                };

                return JsonHelper.Serialize(tmp);
            }
            // 如果token不为空说明当前用户是登录状态,并且当前用户给这个文章点反对,他可能需要取消反对
            else if (isLow != null && isLow.IsDeleted == false)
            {
                isLow.IsDeleted = true;
                isLow.UpdatedTime = DateTime.Now;

                var tmp = new
                {
                    Code = 200,
                    Data = "",
                    Msg = "取消踩一下"
                };

                return JsonHelper.Serialize(tmp);
            }
            // 说明他想重新点赞
            else if (isLow != null && isLow.IsDeleted == true)
            {
                isLow.IsDeleted = false;
                isLow.UpdatedTime = DateTime.Now;
                var tmp = new
                {
                    Code = 200,
                    Data = "",
                    Msg = "踩一下成功"
                };
                return JsonHelper.Serialize(tmp);
            }
            // 如果为空并且token存在,那么说明当前用户是登录状态并且没有给这个文章点过赞那么允许它点赞
            else
            {
                var l = new Article_Low
                {
                    UserId = low.UserId,
                    ArticleId = low.ArticleId
                };
                _Article_LowRepository.Inster(l);
                var tmp = new
                {
                    Code = 200,
                    Data = l,
                    Msg = "踩一下成功"
                };

                return JsonHelper.Serialize(tmp);
            }

        }


        /// <summary>
        /// 文章点赞
        /// </summary>
        /// <param name="like">需要传入:UserId,ArticleId</param>
        /// <returns></returns>
        [HttpPost, Route("InsterLike")]
        public dynamic InsterArticleLike(NewLike_Low_View like)
        {
            // 查找当前用户是否给这个文章点过赞
            var isLike = _Article_LikeRepository.Table.Where(x => x.UserId == like.UserId && x.ArticleId == like.ArticleId).FirstOrDefault();
            var token = like.Token;

            // 如果token不存在那么让他登录
            if (string.IsNullOrEmpty(token) || token == null)
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "您还未登录请登录"
                };

                return JsonHelper.Serialize(tmp);
            }
            // 如果token不为空说明当前用户是登录状态,并且当前用户给这个文章点过赞,他可能需要取消点赞
            else if (isLike != null && isLike.IsDeleted == false)
            {
                isLike.IsDeleted = true;
                isLike.UpdatedTime = DateTime.Now;

                var tmp = new
                {
                    Code = 200,
                    Data = "",
                    Msg = "取消点赞"
                };

                return JsonHelper.Serialize(tmp);
            }
            // 说明他想重新点赞
            else if (isLike != null && isLike.IsDeleted == true)
            {
                isLike.IsDeleted = false;
                isLike.UpdatedTime = DateTime.Now;
                var tmp = new
                {
                    Code = 200,
                    Data = "",
                    Msg = "点赞成功"
                };
                return JsonHelper.Serialize(tmp);
            }
            // 如果为空并且token存在,那么说明当前用户是登录状态并且没有给这个文章点过赞那么允许它点赞
            else
            {
                var l = new Article_Like
                {
                    UserId = like.UserId,
                    ArticleId = like.ArticleId
                };
                _Article_LikeRepository.Inster(l);
                var tmp = new
                {
                    Code = 200,
                    Data = l,
                    Msg = "点赞成功"
                };

                return JsonHelper.Serialize(tmp);
            }

        }


        // 查找48小时最新排行
        [HttpGet, Route("GetfortyeightArticle")]
        public dynamic GetfortyeightArticle()
        {

            var articles = _ArticlesRepository.Table.Where(x => x.IsDeleted == false).ToList();
            var fo = articles.Where(x => ((DateTime.Now - x.CreatedTime).TotalDays <= 2)).OrderByDescending(y => y.CreatedTime).Skip(0).Take(5);
            if (articles == null)
            {
                var tmp = new
                {
                    Code = 200,
                    Data = "",
                    Msg = "暂未查找到48小时内的数据"
                };
                return JsonHelper.Serialize(tmp);
            }
            else
            {
                var tmp = new
                {
                    Code = 200,
                    Data = fo,
                    Msg = "查找到48小时内的数据"
                };
                return tmp;
            }

        }


        // 查找评论最多
        [HttpGet, Route("GetMostComments")]
        public dynamic GetMostComments()
        {

            // 查询文章表
            var a = _ArticlesRepository.Table.Where(x => x.IsDeleted == false).ToList();

            // 根据文章评论数最多排序
            var articles = a.Select(o =>
            {
                var comment = _Article_CommentRepository.Table.Where(x => x.ArticleId == o.Id && x.IsDeleted == false);

                return new
                {
                    articleId = o.Id,
                    comentCount = comment.Where(x => x.ArticleId == o.Id).Count(),
                    articleTitle = o.ArticleTitle
                };
            }).OrderByDescending(x => x.comentCount).Skip(0).Take(4);


            var tmp = new
            {
                Code = 200,
                Data = articles,
                Msg = "查询成功"
            };


            return JsonHelper.Serialize(tmp);

        }


        // 查找浏览次数最多的
        [HttpGet, Route("GetMountView")]
        public dynamic GetMountView()
        {

            var a = _ArticlesRepository.Table.Where(x => x.IsDeleted == false).ToList();

            var articles = a.Select(o =>
            {
                var view = _Article_ViewRepository.Table.Where(x => x.ArticleId == o.Id);

                return new
                {
                    articleId = o.Id,
                    viewCount = view.Where(x => x.ArticleId == o.Id).Count(),
                    articleTitle = o.ArticleTitle
                };

            }).OrderByDescending(x => x.viewCount).Skip(0).Take(4);


            var tmp = new
            {
                Code = 200,
                Data = articles,
                Msg = "查询成功"
            };

            return JsonHelper.Serialize(tmp);
        }



        // 根据文章Id查找文章内容
        [HttpGet, Route("GetArticleById/{id}")]
        public dynamic GetArticleById(int id)
        {

            var article = getArticleMsg(id);

            var tmp = new
            {
                Code = 200,
                Data = article,
                Msg = "根据文章Id查找到对应的文章"
            };
            return JsonHelper.Serialize(tmp);
        }


        // 根据文章Id查找文章内容的方法
        public dynamic getArticleMsg(int id)
        {

            // 当前文章的图片信息
            // var picture = _Article_PictureRepository.Table.Where(x => x.ArticleId == id).FirstOrDefault();
            // 查找当前文章的文章
            var article = _ArticlesRepository.Table.Where(x => x.Id == id).FirstOrDefault();
            // 当前文章的内容 
            var content = _Article_ContentRepository.Table.Where(x => x.ArticleId == id).FirstOrDefault();
            // 当前文章的评论
            var com = _Article_CommentRepository.Table.Where(x => x.ArticleId == id && x.IsDeleted == false).OrderByDescending(x => x.CreatedTime);

            var comment = new List<Object>();

            foreach (var item in com)
            {
                var u = _UsersRepository.Table.Where(x => x.Id == item.UserId).Select(k => k.Username);

                comment.Add(new { user = u, commentContent = item.ArticleCommentContent });
            }

            // 当前文章的评论数
            var commentCount = _Article_CommentRepository.Table.Where(x => x.ArticleId == id && x.IsDeleted == false).Count();
            // 当前文章的点赞数
            var likeCount = _Article_LikeRepository.Table.Where(x => x.ArticleId == id && x.IsDeleted == false).Count();
            // 当前文章的踩一下数
            var lowCount = _Article_LowRepository.Table.Where(x => x.ArticleId == id && x.IsDeleted == false).Count();
            // 当前文章的浏览次数
            var viewCount = _Article_ViewRepository.Table.Where(x => x.ArticleId == id).Count();
            // 查找当前文章的分类名称
            // var category = _Article_CategoryRepository.Table.Where(x => x.Id == article.ArticleCategoryId).FirstOrDefault();

            var tmp = new
            {
                ArticleId = article.Id,
                ArticleContent = content.ArticleContent,
                // HttpUtility.HtmlDecode();
                // ArticlePictureUrl = picture.ArticlePictureUrl,
                // ArticleCategoryName = category.CategoryName,
                ArticleCommentContent = comment,
                ArticleCommentCount = commentCount,
                ArticleIntro = article.ArticleIntro,
                ArticleTitle = article.ArticleTitle,
                ArticleLowCount = lowCount,
                ArticleViewCount = viewCount,
                ArticleLikeCount = likeCount,
                UserId = article.UserId,
                CreateTime = article.CreatedTime
            };

            return tmp;
        }



        // 首页右侧导航栏渲染内容组件
        [HttpPost, Route("PostArticleContent")]
        public dynamic PostArticleContent(ChangeContent model)
        {
            // 查找48小时内最新的文章
            if (model.Content == "new")
            {
                var a = _ArticlesRepository.Table.Where(x => x.IsDeleted == false).ToList();
                var m = a.Where(x => ((DateTime.Now - x.CreatedTime).TotalDays <= 2)).OrderByDescending(y => y.CreatedTime);


                var articles = new List<object>();
                foreach (var item in m)
                {
                    var most = getArticleMsg(item.Id);
                    articles.Add(most);
                }

                var tmp = new
                {
                    Code = 200,
                    Data = articles,
                    Msg = "查找到48小时内的文章"
                };
                return JsonHelper.Serialize(tmp);
            }
            // 10天内浏览次数最多
            else if (model.Content == "most")
            {
                var a = _ArticlesRepository.Table.Where(x => x.IsDeleted == false).ToList();
                // 查找10天内浏览次数最多的文章
                var c = a.Select(o =>
                {
                    // 统计当前的浏览次数
                    var v = _Article_ViewRepository.Table.Where(x => x.ArticleId == o.Id).Count();

                    return new
                    {
                        articleId = o.Id,
                        viewCount = v,
                        createTime = o.CreatedTime
                    };
                }).Where(x => ((DateTime.Now - x.createTime).TotalDays <= 10)).OrderByDescending(x => x.viewCount);


                var articles = new List<object>();
                foreach (var item in c)
                {
                    var view = getArticleMsg(item.articleId);
                    articles.Add(view);
                }

                var tmp = new
                {
                    Code = 200,
                    Data = articles,
                    Msg = "浏览次数最多的"
                };
                return JsonHelper.Serialize(tmp);
            }
            // 10内评论最多
            else if (model.Content == "comments")
            {
                var a = _ArticlesRepository.Table.Where(x => x.IsDeleted == false).ToList();

                // 查找10天内评论最多的文章
                var c = a.Select(o =>
                {
                    // 统计当前文章的评论次数,平且是不计算删除的
                    var v = _Article_CommentRepository.Table.Where(x => x.ArticleId == o.Id && x.IsDeleted == false).Count();

                    return new
                    {
                        articleId = o.Id,
                        commentCount = v,
                        createTime = o.CreatedTime
                    };
                }).Where(x => ((DateTime.Now - x.createTime).TotalDays <= 10)).OrderByDescending(x => x.commentCount);


                var articles = new List<object>();
                foreach (var item in c)
                {
                    var view = getArticleMsg(item.articleId);
                    articles.Add(view);
                }
                var tmp = new
                {
                    Code = 200,
                    Data = articles,
                    Msg = "评论最多"
                };
                return JsonHelper.Serialize(tmp);
            }
            else
            {
                var tmp = new
                {
                    Code = 200,
                    Data = "",
                    Msg = "没有找到当前文章"
                };
                return JsonHelper.Serialize(tmp);
            }

        }

    }

    


}